
import {RankItemData} from './opendata';

declare const wx: any;
const {ccclass, property} = cc._decorator;

@ccclass
export default class RankItem extends cc.Component {

    @property(cc.Label)
    index: cc.Label = null;

    @property(cc.Label)
    nickName: cc.Label = null;

    @property(cc.Label)
    score: cc.Label = null;

    @property([cc.SpriteFrame])
    imgTop: cc.SpriteFrame[] = [];

    @property(cc.Sprite)
    avatar: cc.Sprite = null;

    @property(cc.Sprite)
    imgNo: cc.Sprite = null;

    init (ix:number, data:RankItemData) {
        let ixFrame = this.imgTop[ix]
        if (ixFrame) {
            this.index.node.active = false;
            this.imgNo.spriteFrame = ixFrame;
        } else {
            this.imgNo.node.active = false;
            this.index.string = (ix+1).toString();
        }
        this.nickName.string = data.nickName;
        this.score.string = data.score.toString();
        this.setAvatar(this.avatar, data.avatarUrl);
    }

    setAvatar(sprite: cc.Sprite, url: string) {
        if (!url) {
            return;
        } 
        let image = wx.createImage();
        image.onload = function () {
            let texture = new cc.Texture2D();
            texture.initWithElement(image);
            texture.handleLoadedTexture();
            sprite.spriteFrame = new cc.SpriteFrame(texture);
        };
        image.src = url;
    }
}
